﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace Hands.LoginControl
{
    public class ForcedLoginModule : IHttpModule
    {
        #region IHttpModule 成员

        public void Dispose()
        { }

        public void Init(HttpApplication context)
        {
            context.BeginRequest += beginRequest;
        }

        private delegate IForced Query(string path);
        private delegate bool ForcedToLogin(string path);

        private void beginRequest(object sender, EventArgs e)
        {
            HttpApplication context = (HttpApplication)sender;

            string path = context.Request.Url.AbsolutePath;

            Query query = new Query(new UriBranchQuery().find);
            IForced forced = query.Invoke(path);

            if (forced != null)
            {
                ForcedToLogin forcedToLogin = new ForcedToLogin(forced.isNeedToLogin);

                if (!forcedToLogin.Invoke(path)) return;

                switch (UserState.Way)
                {
                    case Implementation.COOKIE:
                        if (context.Request.Cookies.Get(UserState.Flag) == null)
                        {
                            context.Response.Redirect(UserState.RedirectTo);
                        }
                        break;
                    case Implementation.URI_REWRITE:
                        string userIdentity = context.Request.QueryString[UserState.Flag];
                        if (userIdentity == null || userIdentity.Length == 0)
                        {
                            context.Response.Redirect(UserState.RedirectTo);
                        }
                        break;
                    default:
                        break;
                }
            }
        }

        #endregion
    }
}
